#include <48func.h>
int main(int argc, char *argv[])
{
    // ./3_azhen 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);//ipv4 tcp
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    int reuseArg = 1;
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&reuseArg,sizeof(reuseArg));
    ERROR_CHECK(ret,-1,"setsockopt");
    ret = bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"bind");
    ret = listen(sockfd,10);
    ERROR_CHECK(ret,-1,"listen");
    char buf[4096];
    // 准备好监听集合
    fd_set monitorset;
    FD_ZERO(&monitorset);
    // 把sockfd加入监听
    FD_SET(sockfd,&monitorset);
    int netfd;
    while(1){
        fd_set rdset;
        memcpy(&rdset,&monitorset,sizeof(fd_set));
        select(10,&rdset,NULL,NULL,NULL);//rdset会被修改
        if(FD_ISSET(sockfd,&rdset)){
            struct sockaddr_in clientAddr;
            socklen_t socklen = sizeof(clientAddr);//socklen必须初始化
            netfd = accept(sockfd,(struct sockaddr *)&clientAddr,&socklen);
            ERROR_CHECK(netfd,-1,"accept");
            printf("client ip = %s, port = %d\n",
                   inet_ntoa(clientAddr.sin_addr),
                   ntohs(clientAddr.sin_port));
            // 增加netfd和stdin的监听，取消sockfd的监听
            FD_CLR(sockfd,&monitorset);
            FD_SET(STDIN_FILENO,&monitorset);
            FD_SET(netfd,&monitorset);
        }
        if(FD_ISSET(netfd,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = recv(netfd,buf,sizeof(buf),0);
            if(sret == 0){//说明阿强断开连接啦
                FD_SET(sockfd,&monitorset);
                FD_CLR(STDIN_FILENO,&monitorset);
                FD_CLR(netfd,&monitorset);
                close(netfd);
                printf("wohuihaohaode\n");
            }
            printf("buf = %s\n", buf);
        }
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
            send(netfd,buf,strlen(buf),0);
        }
    }
    return 0;
}






